package com.gateway.filter

import com.yfree.config.YConfig
import com.yfree.global.YController
import org.springframework.beans.factory.annotation.Value
import org.springframework.cloud.gateway.filter.GatewayFilterChain
import org.springframework.cloud.gateway.filter.GlobalFilter
import org.springframework.core.Ordered
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
import java.nio.charset.StandardCharsets

@Component
class MainFilter : YController(), GlobalFilter, Ordered {
    @Value("\${server.port}")
    lateinit var port: String

    override fun filter(exchange: ServerWebExchange?, chain: GatewayFilterChain?): Mono<Void>? {
        println("======================= GatewayFilter,port:$port =======================")
        val request = exchange?.request
        val response = exchange?.response
        if (YConfig.Response.isJsonHeader)
            response?.headers?.add("Content-Type", "application/json; charset=${StandardCharsets.UTF_8.name()}")

//        val gateway_param = request?.queryParams?.getFirst("gateway_param")
//        if (gateway_param != "YFree") {
//            response?.statusCode = HttpStatus.OK
//            return response?.writeWith(Mono.just(response.bufferFactory().wrap(yTojson(code = HttpStatus.UNAUTHORIZED.value(), message = "gateway_param不存在或不正确").toByteArray())))
//        }
        return chain?.filter(exchange)
    }

    override fun getOrder(): Int {
        return 0
    }
}
